<template>
  <t-modal
    class="mL"
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="loading"
    :destroyOnClose="true"
    v-bind="customFooter"
    forceRender
    @ok="ok"
    @cancel="
      () => {
        $refs.previewModal.resetForm(), $emit('cancel');
      }
    "
  >
    <a-spin :spinning="loading">
      <previewModal
        ref="previewModal"
        @getJsonData="getJsonData"
        :isView="type === 'view'"
      />
    </a-spin>
  </t-modal>
</template>

<script>
import previewModal from "@/components/TopVUI/k-form-design/packages/KFormPreview/preview.vue";
import { axios } from "@/utils/request";
import { PageView, RouteView } from "@/layouts";
import { setTypeList, loadTypeList, getTypeList } from "@/utils/formatter";
import { objToParam } from "@/utils/util";
export default {
  name: "TreeList",
  components: {
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    url: {
      type: Object,
      required: true,
    },
    requestMethod: {
      type: String,
    },
    tableDataType: {
      type: String,
    },
    customFooter: {
      type: Object,
      default() {
        return {};
      },
    },
    width: {
      type: Number,
      default: 1000,
    },
    extraParameter: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  provide() {
    // 使用函数的形式，可以访问到 `this`
    return {
      sameValue: false,
    };
  },
  data() {
    return {
      title: "",
      drawingList: {},
      model: {},
      type: "",
      tableUuid: "",
      loading: false,
      fieldList: [],
    };
  },
  methods: {
    // 获取数据
    loadData(e, type, json, info, formName) {
      this.model = {};
      // 多表的情况下后端返回的数据为数组，要处理下数据格式
      if (info?.length) {
        info.forEach((item) => {
          this.model[item.tableField] = item.fieldValue;
        });
      } else if (info) {
        this.model = info;
      }
      this.type = type;
      this.tableUuid = e;
      this.drawingList = JSON.parse(json);
      this.drawingList.list.forEach((item) => {
        if (type === "add") {
          loadTypeList(item);
        } else {
          getTypeList(item, this.model);
        }
      });
      // 调用处理函数
      this.handRules(this.drawingList);
      this.$nextTick(() => {
        if (this.$refs.previewModal) {
          if (type === "add") {
            this.drawingList.formName = formName;
          }
          // this.$refs.previewModal.jsonData = this.drawingList;
          this.$refs.previewModal.setData(this.drawingList);
        }
      });
      this.loading = false;
    },
    // 编辑的时候处理显隐规则绑定后的数据
    handRules(value) {
      const rules = value.config.implicitRules;
      const data = value.list;
      rules?.forEach((rule) => {
        const {
          selectComponentId,
          selectTableId,
          selectValueLId,
          selectValueL,
          selectOtherComponentId,
          selectOtherTableId,
          ifShow,
          ifRequired,
        } = rule;
        const targetComponent = data.find(
          (item) =>
            item.key === selectOtherComponentId ||
            item.model === selectOtherTableId
        );
        let shouldHide = false;
        if (selectComponentId.startsWith("checkbox_")) {
          const selectComponent = data.find(
            (item) =>
              item.key === selectComponentId || item.model === selectTableId
          );
          const arr = selectComponent.options.defaultValue.split(",");
          shouldHide =
            ifShow === "show"
              ? !arr.includes(selectValueLId)
              : arr.includes(selectValueLId);
        } else if (
          selectComponentId.startsWith("input_") ||
          selectComponentId.startsWith("textarea_")
        ) {
          const selectComponent = data.find(
            (item) =>
              item.key === selectComponentId || item.model === selectTableId
          );
          if (selectComponent)
            shouldHide =
              ifShow === "show"
                ? selectComponent.options.defaultValue !== selectValueL
                : selectComponent.options.defaultValue === selectValueL;
        } else {
          const selectComponent = data.find(
            (item) =>
              item.key === selectComponentId || item.model === selectTableId
          );
          if (selectComponent)
            shouldHide =
              ifShow === "show"
                ? selectComponent.options.defaultValue !== selectValueLId
                : selectComponent.options.defaultValue === selectValueLId;
        }
        // 如果是必填组件，根据隐藏状态去除/增加必填属性
        if (targetComponent) {
          if (targetComponent.rules && ifRequired)
            targetComponent.rules[0].required = !shouldHide;
          targetComponent.options.hidden = shouldHide;
        }
        if (shouldHide) {
          targetComponent.options.defaultValue = "";
          const nestedTargetComponent = value.list.find(
            (item) =>
              item.key === selectOtherComponentId ||
              item.model === selectOtherTableId
          );
          nestedTargetComponent.options.hidden = true;
        }
      });
    },
    toHump(name) {
      return name.replace(/\_(\w)/g, function(all, letter) {
        return letter.toUpperCase();
      });
    },
    getJsonData(fieldList, json, code) {
      // this.fieldList = fieldList
      Object.keys(fieldList).forEach((key) => {
        if (
          Object.prototype.toString.call(fieldList[key]) === "[object Object]"
        ) {
          fieldList[key] = JSON.stringify(fieldList[key]);
        }
      });
      this.drawingList.list.forEach((e, index) => {
        let obj = setTypeList(e, fieldList);
        e = obj.e;
        fieldList = obj.list;
        return;
      });
      this.loading = true;
      // let pramar = fieldList;
      let pramar = {
        list: [],
      };
      if (this.tableDataType == 2) {
        for (let obj in fieldList) {
          this.drawingList.list.map((item) => {
            if (item["model"] === obj) {
              pramar.list.push({
                tableName: item.tableName,
                tableField: item.model,
                fieldValue: fieldList[obj],
              });
            }
          });
        }
        if (pramar.list.length) {
          pramar.list = JSON.stringify(pramar.list);
        }
      } else {
        pramar = fieldList;
      }

      pramar.formUuid = this.tableUuid;

      if (this.type === "add") {
        //传递表单-以外参数执行
        /////////////////////////////////////////////////////////////
        if (this.isObjectNotEmpty(this.extraParameter)) {
          pramar.list = this.dealWithExtra(pramar.list);
        }
        /////////////////////////////////////////////////////////////
        pramar.uuid = "";
        let saveUrl = this.splicing(this.url.save, pramar);
        this["$" + this.requestMethod](saveUrl, pramar).then((res) => {
          if (res.statusCode === 200) {
            this.$message.success("新增成功！");
            this.$emit("ok");
            this.$refs.previewModal.resetForm();
          } else {
            this.$message.error(res.message, 1.5);
          }
          setTimeout(() => {
            this.loading = false;
          }, 200);

          // 表单设计全局事件：提交表单后触发
          let fun = eval(code);
          try {
            fun(res);
          } catch (e) {
            //TODO handle the exception
          }
        });
      } else {
        pramar.uuid = this.model.uuid;
        let updateUrl = this.splicing(this.url.update, pramar);
        let { formUuid } = pramar;
        switch (formUuid) {
          case "21B16F64BF29466082347E06DBBB7529":
            this.sendmessage(pramar);
            break;
          default:
            break;
        }

        //传递表单-以外参数执行
        /////////////////////////////////////////////////////////////
        if (this.isObjectNotEmpty(this.extraParameter)) {
          pramar.list = this.dealWithExtra(pramar.list);
        }
        /////////////////////////////////////////////////////////////

        this["$" + this.requestMethod](updateUrl, pramar).then((res) => {
          if (res.statusCode === 200) {
            this.$message.success("修改成功！");
            this.$emit("ok");
            this.$refs.previewModal.resetForm();
          } else {
            this.$message.error(res.message, 1.5);
          }
          setTimeout(() => {
            this.loading = false;
          }, 200);

          // 表单设计全局事件：提交表单后触发
          let fun = eval(code);
          try {
            fun(res);
          } catch (e) {
            //TODO handle the exception
          }
        });
      }
    },
    splicing(url, pramar) {
      if (this.requestMethod === "get" && url.indexOf("?") > -1) {
        url = url.replace("?", objToParam(pramar) || "");
      } else if (this.requestMethod === "get" && url.indexOf("?") === -1) {
        url = url + objToParam(pramar);
      }
      return url;
    },
    ok() {
      this.$refs.previewModal.getJsonData();
    },
    //项目概况-发送短信接口
    sendmessage(data) {
      let { list, uuid } = data;
      let soucre = JSON.parse(list ?? "[]");
      let obj = soucre.find((v) => v.tableField == "pro_status");
      let formJson = {
        uuid,
        proStatus: obj.fieldValue,
      };
      axios
        .post(`/probusiness/project-main/updateProStatusSendSms`, formJson, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {})
        .catch((_) => {})
        .finally((_) => {});
    },
    //处理额外参数
    isObjectNotEmpty(obj) {
      return (
        typeof obj === "object" && obj !== null && Object.keys(obj).length > 0
      );
    },
    dealWithExtra(data = "[]") {
      let list = JSON.parse(data);
      let { extraParameter } = this;
      for (let key in extraParameter) {
        if (key != "tableName") {
          list.push({
            tableName: extraParameter.tableName,
            tableField: key,
            fieldValue: extraParameter[key],
          });
        }
      }
      return JSON.stringify(list);
    },
  },
};
</script>

<style lang="scss" scoped>
.ant-form {
  height: auto;
  width: 100%;
}
::v-deep .ant-modal-body {
  max-height: 700px;
  overflow: auto;
}
/* .mL .ant-modal-footer {
		border: none !important;
	} */
</style>
